package com.example.service;

import com.example.config.SysMQConfig;
import com.example.listener.handler.SysMQMessageListenerHandler;
import com.example.startup.SysMQStartUpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/****
 *
 * MQ的启动类
 */
@Service
public class SysMQLoadServiceImpl implements SysMQLoadService, InitializingBean, ApplicationListener<ContextRefreshedEvent>, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    public static final String MQ_START_UP_BEAN_NAME = "sysMQStartUpService";

    @Resource
    private SysBeanService sysBeanService;

    @Resource
    private SysMQConfig sysMQConfig;

    @Resource
    private SysMQMessageListenerHandler sysMQMessageListenerHandler;

    @Resource
    private SysServerService sysServerService;

    private SysMQStartUpService sysMQStartUpService;

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            Class<?> startClass = Class.forName(sysMQConfig.getLoadClass());
            this.sysMQStartUpService = (SysMQStartUpService) startClass.newInstance();
            this.sysMQStartUpService.init(sysMQConfig, sysMQMessageListenerHandler, sysServerService);
            sysBeanService.registerSingleton(MQ_START_UP_BEAN_NAME, sysMQStartUpService);
        } catch (Exception e) {
            logger.warn("加载MQ启动类初始化出错: " + e.getMessage());
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            try {
                this.sysMQStartUpService.start();
            } catch (Exception e) {
                logger.warn("加载MQ启动类启动出错: " + e.getMessage());
            }
        }
    }

    @Override
    public void destroy() throws Exception {
        try {
            this.sysMQStartUpService.stop();
        } catch (Exception e) {
            logger.warn("加载MQ启动类关闭出错: " + e.getMessage());
        }
    }
}
